import { RetweetOutlined } from "@ant-design/icons"
import { Button, Divider, Flex, Typography } from "antd"
import { FC, useCallback, useEffect, useState } from "react"
import { useSelector } from "react-redux"

import { queryMemberBalance, queryPlayerBetHistorySum, queryPlayerTop3 } from "@/api/member"
import { IBalanceInfo, IDataBet } from "@/api/member/types"
import { IMemberParams } from "@/api/risk/types"
import { DataList } from "@/components/common"
import { useDigital } from "@/hooks"
import { UserState } from "@/interface/user/user"
import { useLocale } from "@/locales"
import { handleNumber } from "@/utils/util"

import { CheckTheDetailModal } from "./components/CheckTheDetailModal"
import { ManualAdjustmentModal } from "./components/ManualAdjustmentModal"
import { FinanceInfoContainer } from "./styles"
import { columnsFinaceInfoBet, columnsFinaceInfoWinOrLose } from "./TableInfo"

export const FinaceInfo: FC<{ data: IMemberParams }> = ({ data }) => {
	const [dataFinaceInfo, setDataFinaceInfo] = useState([])
	const [isBetTable, setIsBetTable] = useState<boolean>(false)
	const [dataBet, setDataBet] = useState<IDataBet>({
		betAmount: 0,
		companyNetAmount: 0,
		discountAmount: 0,
		lastNetAmount: 0,
		netAmount: 0,
		payAmount: 0,
		returnWaterAmount: 0,
		validBetAmount: null
	})
	const [balanceInfoState, setBalanceInfoState] = useState<IBalanceInfo | null>(null)
	const { formatMessage } = useLocale()
	const { renderFormat, renderColor } = useDigital()

	const handleTableFinaceInfo = useCallback(
		async (value: number) => {
			const updatedParam = {
				merchantId: data.merchantId,
				userName: data.username,
				topProxyName: data.topProxyName,
				userId: data.userId,
				currency: data.currency,
				clubId: data.clubId,
				businessModel: data.businessModel,
				orderKey: value
			}
			const [err, playerTop3Res] = await queryPlayerTop3(updatedParam)
			if (!err) setDataFinaceInfo(playerTop3Res)
		},
		[data]
	)

	const handleQueryPlayerBetHistorySum = useCallback(async () => {
		const body = {
			merchantId: data.merchantId,
			userName: data.username,
			topProxyName: data.topProxyName,
			userId: data.userId,
			currency: data.currency,
			clubId: data.clubId,
			businessModel: data.businessModel
		}
		const [err, playerBetHistorySumRes] = await queryPlayerBetHistorySum(body)
		if (!err) setDataBet(playerBetHistorySumRes)
	}, [data])

	const handleQueryMemberBalance = useCallback(async () => {
		const body = {
			merchantId: data.merchantId,
			userName: data.username,
			topProxyName: data.topProxyName,
			userId: data.userId,
			currency: data.currency,
			clubId: data.clubId,
			businessModel: data.businessModel
		}
		const [err, memberBalanceRes] = await queryMemberBalance(body)
		if (!err) {
			setBalanceInfoState(memberBalanceRes)
		}
	}, [data])

	const handleGetFinaceInfo = async () => {
		await handleTableFinaceInfo(1)
		await handleQueryPlayerBetHistorySum()
		await handleQueryMemberBalance()
	}

	useEffect(() => {
		// this will help to refresh pagination when upper actions are changed
		if (data.userId) handleGetFinaceInfo()
	}, [data])

	return (
		<FinanceInfoContainer>
			<Flex gap={20} align="center">
				<Typography className="title-bold">{formatMessage({ id: "member.finace_info.cash_wallet" })}</Typography>
				<Button icon={<RetweetOutlined />} onClick={handleQueryMemberBalance} type="primary">
					{formatMessage({ id: "member.refresh" })}
				</Button>
			</Flex>
			<Flex align="center" justify="space-between" className="width-eight">
				<Flex gap={5} align="center">
					<Typography>{formatMessage({ id: "member.finace_info.cash_wallet_balance" })}:</Typography>
					<Typography>{handleNumber(balanceInfoState?.currency || "", balanceInfoState?.cash?.toString() || "")}</Typography>
				</Flex>
				<Flex gap={5} align="center">
					<Typography>{formatMessage({ id: "member.finace_info.withdraw_frozen_balance" })} :</Typography>
					<Typography>{handleNumber(balanceInfoState?.currency || "", balanceInfoState?.frozen?.toString() || "")}</Typography>
				</Flex>
				<Flex gap={5} align="center">
					<Typography>{formatMessage({ id: "member.finace_info.bureau_service_fee_frozen_amount" })}:</Typography>
					<Typography>
						{handleNumber(balanceInfoState?.currency || "", balanceInfoState?.texasFreezeAmount?.toString() || "")}
					</Typography>
				</Flex>
			</Flex>
			<Divider />
			{data.businessModel === 2 && (
				<>
					<Flex gap={20} align="center">
						<Typography className="title-bold">{formatMessage({ id: "member.finace_info.credit_wallet" })}</Typography>
						<Button icon={<RetweetOutlined />} onClick={handleQueryMemberBalance} type="primary">
							{formatMessage({ id: "member.refresh" })}
						</Button>
					</Flex>
					<Flex align="center" justify="space-between" className="width-eight">
						<Flex gap={5} align="center">
							<Typography>{formatMessage({ id: "member.finace_info.available_credit" })}:</Typography>
							<Typography>
								{handleNumber(balanceInfoState?.currency || "", balanceInfoState?.creditAvailable?.toString() || "")}
							</Typography>
						</Flex>
						<Flex gap={5} align="center">
							<Typography>{formatMessage({ id: "member.finace_info.credits" })} :</Typography>
							<Typography>
								{handleNumber(balanceInfoState?.currency || "", balanceInfoState?.creditTotal?.toString() || "")}
							</Typography>
						</Flex>
						<Flex gap={5} align="center">
							<Typography>{formatMessage({ id: "member.finace_info.accounts_payable" })}:</Typography>
							<Typography>
								{handleNumber(balanceInfoState?.currency || "", balanceInfoState?.returnLoan?.toString() || "")}
							</Typography>
						</Flex>
					</Flex>
					<Divider />
				</>
			)}
			<Typography className="title-bold">{formatMessage({ id: "member.finace_info.withdrawal_information" })}</Typography>
			<WithdrawInfo data={data} balanceInfo={balanceInfoState} />
			<Divider />
			<Typography className="title-bold">
				{formatMessage({ id: "member.finace_info.deposit_and_withdrawal_information" })}:
			</Typography>
			<Flex align="center" justify="space-between" className="width-eight">
				<Flex gap={5} align="center">
					<Typography>{formatMessage({ id: "member.finace_info.total_deposit" })} :</Typography>
					<Typography>
						{handleNumber(
							balanceInfoState?.currency || "",
							balanceInfoState?.depositWithdrawSummaryDTO?.depositTotal?.toString() || ""
						)}
					</Typography>
				</Flex>
				<Flex gap={5} align="center">
					<Typography>{formatMessage({ id: "member.finace_info.number_of_deposits" })} :</Typography>
					<Typography>{balanceInfoState?.depositWithdrawSummaryDTO?.depositTimes || "0"}</Typography>
				</Flex>
				<Flex gap={5} align="center">
					<Typography>{formatMessage({ id: "member.finace_info.latest_deposit" })}:</Typography>
					<Typography>
						{handleNumber(
							balanceInfoState?.currency || "",
							balanceInfoState?.depositWithdrawSummaryDTO?.lastDeposit?.toString() || ""
						)}
					</Typography>
				</Flex>
			</Flex>
			<Flex align="center" justify="space-between" className="width-eight">
				<Flex gap={5} align="center">
					<Typography>{formatMessage({ id: "member.finace_info.total_withdrawal_amount" })}:</Typography>
					<Typography>
						{handleNumber(
							balanceInfoState?.currency || "",
							balanceInfoState?.depositWithdrawSummaryDTO?.withdrawTotal?.toString() || ""
						)}
					</Typography>
				</Flex>

				<Flex gap={5} align="center">
					<Typography>
						{formatMessage({ id: "member.finace_info.number_of_withdrawals" })} :{" "}
						{balanceInfoState?.depositWithdrawSummaryDTO?.withdrawTimes?.toString() || 0} (
						{formatMessage({ id: "member.finace_info.ordinary" })}{" "}
						{balanceInfoState?.depositWithdrawSummaryDTO?.ordinaryWithdrawTimes || 0}{" "}
						{formatMessage({ id: "member.finace_info.second" })}
						{" , "}
						{formatMessage({ id: "member.finace_info.large" })}{" "}
						{balanceInfoState?.depositWithdrawSummaryDTO?.bigWithdrawTimes || 0}{" "}
						{formatMessage({ id: "member.finace_info.second" })})
					</Typography>
				</Flex>
				<div></div>
			</Flex>
			<Divider />
			<Typography className="title-bold">{formatMessage({ id: "member.finace_info.betting_information" })}:</Typography>
			<Flex align="center" justify="space-between" className="width-eight">
				<Flex gap={10}>
					<Typography>{formatMessage({ id: "member.finace_info.total_bet" })}:</Typography>
					<Typography>{renderFormat(dataBet ? dataBet.betAmount : 0)} </Typography>
				</Flex>
				<Flex gap={10}>
					<Typography>{formatMessage({ id: "member.finace_info.players_win_or_lose" })}:</Typography>
					<Typography>{renderColor(dataBet ? dataBet.netAmount : 0)} </Typography>
				</Flex>

				<Flex gap={10}>
					<Typography>{formatMessage({ id: "member.finace_info.the_company_total_wins_and_losses" })}:</Typography>
					<Typography>{renderColor(dataBet ? dataBet.companyNetAmount : 0)} </Typography>
				</Flex>
			</Flex>
			<Flex gap={5} align="center" className="top-ten">
				<Typography>{formatMessage({ id: "member.finace_info.member_rebate" })}:</Typography>
				<Typography>{dataBet ? renderFormat(dataBet.returnWaterAmount) : "$0"}</Typography>
			</Flex>
			<Divider />
			<Flex gap={10} align="center">
				<Typography className="title-bold">
					{formatMessage({ id: "member.finace_info.statistics_of_the_top_3_venues" })}{" "}
				</Typography>
				<Button
					icon={<RetweetOutlined />}
					onClick={() => {
						handleTableFinaceInfo(1)
						setIsBetTable(false)
					}}
					type="primary"
				>
					{formatMessage({ id: "member.finace_info.win_or_lose" })}
				</Button>
				<Button
					icon={<RetweetOutlined />}
					onClick={() => {
						handleTableFinaceInfo(2)
						setIsBetTable(true)
					}}
					type="primary"
				>
					{formatMessage({ id: "member.finace_info.bet" })}
				</Button>
			</Flex>

			<DataList
				maxHeight="300px"
				data={dataFinaceInfo}
				columns={
					isBetTable ? columnsFinaceInfoBet(formatMessage, renderColor) : columnsFinaceInfoWinOrLose(formatMessage, renderColor)
				}
				bordered
				size="middle"
				rowKey="id123"
				pagination={{
					pageSize: 50,
					current: 1,
					total: 0
				}}
			/>
		</FinanceInfoContainer>
	)
}

const WithdrawInfo = ({ balanceInfo, data }: { balanceInfo: IBalanceInfo | null; data: IMemberParams }) => {
	const permission = useSelector((state: { user: UserState }) => state.user.permissions) || []
	const { formatMessage } = useLocale()
	if (balanceInfo?.withdrawLimitInfo?.withdrawLimitType === 1)
		return (
			<Flex align="center" justify="space-between" className="width-eight">
				<Flex gap={5} align="center" className="width-eight">
					<Typography>{formatMessage({ id: "agent.withdraw_limit" })}:</Typography>
					<Typography>{formatMessage({ id: "member.finace_info.blling_limits" })}</Typography>
				</Flex>
				<Flex gap={5} align="center" className="width-eight">
					<Typography>{formatMessage({ id: "agent.remaining_withdrawable_amount" })}:</Typography>
					<Typography>
						{handleNumber(balanceInfo?.currency || "", balanceInfo?.withdrawLimitInfo?.withdrawRemainAmount?.toString() || "")}
					</Typography>
				</Flex>
				<Typography className="width200"></Typography>
			</Flex>
		)
	if (balanceInfo?.withdrawLimitInfo?.withdrawLimitType === 2)
		return (
			<Flex align="center" justify="space-between" className="width-eight">
				<Flex vertical gap={10}>
					<Flex gap={5} align="center">
						<Typography>{formatMessage({ id: "funds.capital_adjustment.withdraw_limit_type" })}:</Typography>
						<Typography>{formatMessage({ id: "member.finace_info.turnover_limits" })}</Typography>
					</Flex>
					<Flex gap={5} align="center">
						<Typography>{formatMessage({ id: "member.finace_info.withdrawal_water_adjust" })}:</Typography>
						<Typography>
							{handleNumber(balanceInfo?.currency || "", balanceInfo?.withdrawLimitInfo?.totalAdjust?.toString() || "")}
						</Typography>

						<CheckTheDetailModal value={formatMessage({ id: "common.check_detail" })} data={data} />
					</Flex>
				</Flex>

				<Flex vertical gap={10}>
					<Flex gap={5} align="center">
						<Typography>{formatMessage({ id: "funds.capital_adjustment.need_valid_water" })}:</Typography>
						<Typography>
							{handleNumber(balanceInfo?.currency || "", balanceInfo?.withdrawLimitInfo?.validBillAmount?.toString() || "")}
						</Typography>
						<ManualAdjustmentModal
							value={permission?.includes("90150034") && formatMessage({ id: "member.finace_info.person_adjust" })}
							data={data}
						/>
					</Flex>

					<Flex gap={5} align="center">
						<Typography>{formatMessage({ id: "member.finace_info.finish_det_onWater" })}:</Typography>
						<Typography>
							{handleNumber(balanceInfo?.currency || "", balanceInfo?.withdrawLimitInfo?.completeBillAmount?.toString() || "")}
						</Typography>
					</Flex>
				</Flex>
				<Flex vertical gap={10}>
					<Typography style={{ visibility: "hidden" }}>temp</Typography>
					<Flex gap={5} align="center">
						<Typography>{formatMessage({ id: "member.finace_info.water_start_count_time" })}:</Typography>
						<Typography>{balanceInfo?.withdrawLimitInfo?.billStartTime?.toString() || ""}</Typography>
					</Flex>
				</Flex>
			</Flex>
		)
	return <></>
}
